<?php

function img_getCaptcha(): array
{
    // 生成随机验证码
    $code = '';
    for ($i = 0; $i < 6; $i++) {
        $code .= chr(rand(97, 122)); // 生成随机小写字母
    }

    // 创建一个验证码图片
    $width = 60; // 图片宽度
    $height = 30; // 图片高度

    // 创建画布
    $image = imagecreatetruecolor($width, $height);

    // 设置背景颜色
    $bgColor = imagecolorallocate($image, 255, 255, 255);
    imagefill($image, 0, 0, $bgColor);

    // 设置验证码颜色
    $textColor = imagecolorallocate($image, 0, 0, 0);

    // 在画布上绘制验证码
    imagestring($image, 8, 5, 5, $code, $textColor);

    // 添加干扰线
    for ($i = 0; $i < 2; $i++) {
        $lineColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
        imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
    }

    // 将图片内容转换为Base64编码
    ob_start();
    imagepng($image);
    $imageData = ob_get_clean();
    $base64 = base64_encode($imageData);
    $captchaId = uniqid("", false);
    $captchaData = [
        "type" => "Alphabet",
        "code" => $code,
    ];
    //写入缓存5分钟有效
    cache()->set("captcha_$captchaId", $captchaData, 300);
    return ["captchaId" => "", "img" => $base64];
}

/**验证图片验证码,
 * @param $data ["id"="xxxxxx","code"=>"aaaa", "Type"="Alphabet"]
 * @return array
 */
function img_validateCaptcha($data): array
{
    //校验验证码数据
    $rules = getKeyDefaultRule(array(
        "id" => "require|min:10|max:25",
        "Type" => "require|between:0,3",
        "code" => "require|length:6",
    ));

    validate()->message(getValidateMessage($rules));
    if (!validate()->check($data["captcha"], $rules)) {
        return ["err" => validate()->getError()];
    }
    $captchaData = cache()->get("captcha_" . $data["Id"]);
    cache()->rm("captcha_" . $data["id"]); //删除防复用

    //检测验证码不正确, 或不是该类型的验证码,
    if ($data["code"] !== $captchaData["code"] || $data["type"] !== "Alphabet") {
        return ["err" => "验证码错误请重新输入"];
    }

    return [];
}


//图片缩放
function img_resizeImage($originalImagePath/*原始图片路径*/, $targetWidth/*目标宽度*/, $targetHeight/*目标高度*/)
{
    // 获取原始图片的信息
    $originalImageInfo = getimagesize($originalImagePath);
    $originalWidth = $originalImageInfo[0];
    $originalHeight = $originalImageInfo[1];

    // 根据原始图片的格式创建对应的图片资源
    switch ($originalImageInfo[2]) {
        case IMAGETYPE_JPEG:
            $originalImage = imagecreatefromjpeg($originalImagePath);
            break;
        case IMAGETYPE_PNG:
            $originalImage = imagecreatefrompng($originalImagePath);
            break;
        case IMAGETYPE_BMP:
            $originalImage = imagecreatefrombmp($originalImagePath);
            break;
        case IMAGETYPE_GIF:
            $originalImage = imagecreatefromgif($originalImagePath);
            break;
        default:
            // 不支持的图片格式
            return [];
    }

    // 创建目标图片资源
    $targetImage = imagecreatetruecolor($targetWidth, $targetHeight);

    // 将原始图片缩放到目标尺寸
    imagecopyresampled($targetImage, $originalImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $originalWidth, $originalHeight);


    // 将目标图片保存到字节数组
    ob_start();
    switch ($originalImageInfo[2]) {
        case IMAGETYPE_JPEG:
            imagejpeg($targetImage, null, 100);
            break;
        case IMAGETYPE_PNG:
            imagepng($targetImage, null, 9);
            break;
        case IMAGETYPE_BMP:
            imagebmp($targetImage, null, 9);
            break;
        case IMAGETYPE_GIF:
            imagegif($targetImage, null);
            break;
        default:
            // 不支持的图片格式
            return false;
    }
    $imageData = ob_get_clean();

    // 生成新文件名
    $pathInfo = pathinfo($originalImagePath);

    // 释放资源
    imagedestroy($originalImage);
    imagedestroy($targetImage);

    return [
        'img' => $imageData,
        'extension' => $pathInfo['extension'],
        'width' => $targetWidth,
        'height' => $targetHeight,
        'mime' => $originalImageInfo['mime']
    ];
}
